package com.gywj.race.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gywj.race.config.dao.Assembler;
import com.gywj.race.config.exception.BaseException;
import com.gywj.race.config.page.PageResult;
import com.gywj.race.dto.*;
import com.gywj.race.entity.*;
import com.gywj.race.mapper.*;
import com.gywj.race.util.HttpClient;
import com.gywj.race.util.IdWorker;
import com.gywj.race.util.ObjectUtil;
import com.gywj.race.util.oss.OssUtil;
import com.gywj.race.wxPay.MyWxPayConfig;
import com.gywj.race.wxPay.WXPay;
import com.gywj.race.wxPay.WXPayConstants;
import com.gywj.race.wxPay.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
import java.util.List;

/**
 * The type Paticipant service.
 */
@Service
public class PaticipantService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Resource
    private ParticipantInfoBaseBestScoreMapper participantInfoBaseBestScoreMapper;

    @Resource
    private ParticipantInfoAuditStatusMapper participantInfoAuditStatusMapper;

    @Resource
    private ParticipantTeamMapper participantTeamMapper;

    @Resource
    private ParticipantInfoBaseMapper participantInfoBaseMapper;

    @Resource
    private ParticipantRaceMapper participantRaceMapper;

    @Resource
    private ParticipantInfoAuditMapper participantInfoAuditMapper;

    @Resource
    private ParticipantInfoAuditProcessMapper participantInfoAuditProcessMapper;

    @Resource
    private ParticipantPageParamMapper participantPageParamMapper;

    @Resource
    private EventPriceMapper eventPriceMapper;

    @Resource
    private ExpandMapper expandMapper;

    @Resource
    private IdWorker idWorker;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private BillDetailMapper billDetailMapper;

    @Resource
    private EventGroupMapper eventGroupMapper;

    @Resource
    private SendSmsService sendSmsService;

    @Resource
    private EventInformationMapper eventInformationMapper;
    @Autowired
    private OssUtil ossUtil;

    /**
     * 获取参与者信息审核状态列表
     *
     * @return the organizer list
     */
    public List<ParticipantInfoAuditStatus> getParticipantInfoAuditStatusList() {
        try {
            List<ParticipantInfoAuditStatus> participantInfoAuditStatuses
                    = participantInfoAuditStatusMapper
                    .selectByExample(new ParticipantInfoAuditStatusExample());
            return participantInfoAuditStatuses;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 添加最好成绩的图片和信息
     *
     * @param paticipantInfoBaseBestScore the paticipant info base best score
     */
    public void addParticipantInfoBaseBestScore(ParticipantInfoBaseBestScore paticipantInfoBaseBestScore) {
        try {
            participantInfoBaseBestScoreMapper.insertSelective(paticipantInfoBaseBestScore);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 添加团队
     *
     * @param participantTeam the participant team
     */
    public void addParticipantTeam(ParticipantTeam participantTeam) {
        try {
            String name = participantTeam.getName();
            ParticipantTeamExample participantTeamExample = new ParticipantTeamExample();
            participantTeamExample.createCriteria().andNameEqualTo(name);
            List<ParticipantTeam> participantTeams = participantTeamMapper.selectByExample(participantTeamExample);
            if (!CollectionUtils.isEmpty(participantTeams)) {
                throw new BaseException("该团队已添加，请勿重复添加");
            }
            participantTeamMapper.insertSelective(participantTeam);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 获取参赛团队列表
     *
     * @param eventId the event id
     * @return the participant team list
     */
    public List<ParticipantTeam> getParticipantTeamListByEventId(Integer eventId) {
        try {
            ParticipantTeamExample participantTeamExample = new ParticipantTeamExample();
            participantTeamExample.createCriteria().andEventIdEqualTo(eventId);
            List<ParticipantTeam> participantInfoAuditStatuses
                    = participantTeamMapper
                    .selectByExample(participantTeamExample);
            return participantInfoAuditStatuses;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    /**
     * 插入信息
     * <p>
     * 填错了可以申请退款 然后重新填报
     *
     * @param paticipantAddDto the paticipant add dto
     */
    public Map<String, Object> addParticipantInfo(PaticipantDto paticipantAddDto, HttpServletRequest request) {
        try {
            logger.info("=============paticipantAddDto=============" + ObjectUtil.toString(paticipantAddDto));
            Integer groupId = paticipantAddDto.getGroupId();
            EventGroup eventGroup = eventGroupMapper.selectByPrimaryKey(groupId);
            Integer end = eventGroup.getEnd();
            Integer currentMax = eventGroup.getCurrentMax();

            if (end.equals(currentMax)) {
                throw new BaseException("该组别报名人员已满，请联系管理员");
            }

            Integer eventPriceId = paticipantAddDto.getEventPriceId();
            EventPrice eventPrice = eventPriceMapper.selectByPrimaryKey(eventPriceId);

            BigDecimal price = eventPrice.getPrice();


            //创建参与者信息
            ParticipantInfoBase participantInfoBase = new ParticipantInfoBase();
            Assembler.assemble(paticipantAddDto, participantInfoBase);

            logger.info("=========participantInfoBase========" + ObjectUtil.toString(participantInfoBase));
            participantInfoBaseMapper.insertSelective(participantInfoBase);

            //创建参赛信息
            ParticipantRace participantRace = new ParticipantRace();
            Assembler.assemble(paticipantAddDto, participantRace);
            participantRace.setOpenId(paticipantAddDto.getOpenId());
            Integer infoBaseId = participantInfoBase.getId();
            participantRace.setPibId(infoBaseId);
            participantRace.setAmount(price);
            //待缴费状态 插入成功，然后调用支付
            participantRace.setStatus(0);
            logger.info("=========participantRace========" + ObjectUtil.toString(participantRace));
            participantRaceMapper.insertSelective(participantRace);

            //创建最好比赛成绩信息
            ParticipantInfoBaseBestScore participantInfoBaseBestScore = new ParticipantInfoBaseBestScore();
            Assembler.assemble(paticipantAddDto, participantInfoBaseBestScore);
            String pic = paticipantAddDto.getPic();
            if (!StringUtils.isEmpty(pic)) {
                //去掉结尾的 "，"
                pic = pic.substring(0, pic.length() - 1);
                participantInfoBaseBestScore.setPic(pic);
                participantInfoBaseBestScore.setPibId(infoBaseId);
                participantInfoBaseBestScoreMapper.insertSelective(participantInfoBaseBestScore);
            }
            //插入审核信息表
            ParticipantInfoAudit participantInfoAudit = new ParticipantInfoAudit();
            participantInfoAudit.setPibId(infoBaseId);
            Integer raceId = participantRace.getId();
            participantInfoAudit.setPrId(raceId);

            //默认审核人 1
            participantInfoAudit.setAuditEmployeeId(1);
            participantInfoAudit.setAuditTime(new Date());

            //待缴费状态 插入成功，然后调用支付
            participantInfoAudit.setStatus(0);
            participantInfoAuditMapper.insertSelective(participantInfoAudit);

            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("pibId", infoBaseId);
            resultMap.put("raceId", raceId);
            resultMap.put("eventPriceId", eventPriceId);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    //调用支付
    public Map wxpay(Integer pib, Integer eventPriceId, Integer tradeType, String openId) {
        try {
            String tradeNo = String.valueOf(idWorker.nextId());
            Orders order = new Orders();
            order.setTradeNo(tradeNo);
            order.setPibId(pib);
            order.setEventPriceId(eventPriceId);
            order.setStatus(0);
            EventPrice eventPrice = eventPriceMapper.selectByPrimaryKey(eventPriceId);
            if (ObjectUtil.isNullObj(eventPrice)) {
                throw new BaseException("套餐信息不存在");
            }
            order.setAmont(eventPrice.getPrice());
            //todo 目前只做微信支付
            order.setTradeType(tradeType);
            order.setTradeTime(new Date());
            //插入订单表
            ordersMapper.insertSelective(order);
            //调起微信支付
            Map undefined = undefined(openId, eventPrice.getPrice().multiply(new BigDecimal("100")).intValue(), tradeNo);
            return undefined;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }

    }


    public void cancelOrder(String out_trade_no) {
        try {


            String xmlParam = WXPayUtil.closeOrder(out_trade_no);
            Map<String, String> mapResult = doPost("https://api.mch.weixin.qq.com/pay/closeorder", xmlParam);
            //判断返回状态码return_code
            if (WXPayConstants.WX_RETURN_CODE_FAIL.equals(mapResult.get(WXPayConstants.FIELD_RETURN_CODE))) {
                throw new BaseException(mapResult.get("return_msg"));
            }
            //判断业务结果result_code
            if (WXPayConstants.WX_RESULT_CODE_FAIL.equals(mapResult.get(WXPayConstants.FIELD_RESULT_CODE))) {
                throw new BaseException(mapResult.get("err_code_des"));
            }

            OrdersExample ordersExample = new OrdersExample();
            ordersExample.createCriteria().andTradeNoEqualTo(out_trade_no);
            List<Orders> orders = ordersMapper.selectByExample(ordersExample);
            if (CollectionUtils.isEmpty(orders)) {
                throw new BaseException("取消失败,订单不存在");
            }
            Orders orders1 = orders.get(0);
            orders1.setStatus(-1);
            ordersMapper.updateByPrimaryKey(orders1);

            Integer pibId = orders1.getPibId();
            ParticipantRaceExample participantRaceExample = new ParticipantRaceExample();
            participantRaceExample.createCriteria().andPibIdEqualTo(pibId);
            List<ParticipantRace> participantRaces = participantRaceMapper.selectByExample(participantRaceExample);
            if (CollectionUtils.isEmpty(participantRaces)) {
                throw new BaseException("取消失败,比赛信息不存在");
            }

            ParticipantRace participantRace = participantRaces.get(0);
            participantRace.setStatus(-2);
            participantRaceMapper.updateByPrimaryKeySelective(participantRace);

            updateAuditDataState(pibId, participantRace.getId(), 0, -2, 1);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("取消订单异常");
        }

    }

    //成功后 调用的更新状态的接口，修改状态为待审核，插入审核流程表
    public void paySuccess(Integer pibId, Integer raceId, String tradeNo, HttpServletRequest request) {
        try {
            ParticipantRace participantRace = new ParticipantRace();
            participantRace.setId(raceId);
            // 支付成功，修改比赛信息状态为 1 待审核，
            participantRace.setStatus(1);

            // 安排编号
            String participantCode = getParticipantCode(raceId);
            participantRace.setParticipantCode(participantCode);

            participantRaceMapper.updateByPrimaryKeySelective(participantRace);

            // 修改审核表 该信息的当前状态为 1 待审核，
            // 新增审核流程 从 待支付0 -> 待审核1
            updateAuditDataState(pibId, raceId, 0, 1, 1);
            OrdersExample ordersExample = new OrdersExample();
            ordersExample.createCriteria().andTradeNoEqualTo(tradeNo);
            List<Orders> orders = ordersMapper.selectByExample(ordersExample);
            if (CollectionUtils.isEmpty(orders)) {
                throw new BaseException("订单号不存在");
            }
            Orders order = orders.get(0);
            order.setStatus(1);
            //更新订单状态
            ordersMapper.updateByPrimaryKey(order);

            //插入账单表
            BillDetail billDetail = new BillDetail();
            billDetail.setPibId(pibId);
            billDetail.setOrderId(order.getId());
            billDetail.setBeforeMoney(BigDecimal.ZERO);
            billDetail.setMoney(order.getAmont());
            billDetail.setAfterMoney(order.getAmont());
            billDetail.setOrderType(1);
            billDetail.setOperateTime(new Date());
            billDetail.setOrderStatus(1);

            billDetailMapper.insertSelective(billDetail);

            Map<String, Object> page2Info = getPage2Info(raceId);
            Map<String, Object> paramMap = Maps.newHashMap();
            String mobile = (String) page2Info.get("personal_mobile");
            paramMap.put("name", page2Info.get("name"));
            paramMap.put("event_info_name", page2Info.get("event_info_name"));
            paramMap.put("participant_code", page2Info.get("participant_code"));
            paramMap.put("event_info_begin_time", page2Info.get("event_info_begin_time"));
            paramMap.put("event_info_place", page2Info.get("event_info_place"));
            //todo 暂时取消发送短信 改手动
//            sendSmsService.sendSms(mobile, paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    //驳回
    public void refuse(Integer infoId, Integer raceId, HttpServletRequest request) {
        try {
            ParticipantRace race = participantRaceMapper.selectByPrimaryKey(raceId);
            if (!race.getStatus().equals(1)) {
                throw new BaseException("该状态下不符合报名审核通过的条件");
            }

            ParticipantRace participantRace = new ParticipantRace();
            participantRace.setId(raceId);

            // 支付成功后，信息不合格，驳回重填，状态为 -1报名驳回状态 ，
            participantRace.setStatus(-1);
            participantRaceMapper.updateByPrimaryKeySelective(participantRace);

            // 修改审核表 该信息的当前状态为 1 待审核，
            // 新增审核流程 从 待支付0 -> 待审核1
            Employees employee = (Employees) request.getSession().getAttribute("employee");


            //调用微信退款 refund 付款金额原路返回
            BigDecimal amount = race.getAmount();

            int total_fee_cent = amount.multiply(new BigDecimal("100")).intValue();
            if (total_fee_cent != 0) {
                Integer pibId = race.getPibId();
                Integer eventPriceId = race.getEventPriceId();

                OrdersExample ordersExample = new OrdersExample();
                ordersExample.createCriteria()
                        .andPibIdEqualTo(pibId)
                        .andEventPriceIdEqualTo(eventPriceId);

                List<Orders> orders = ordersMapper.selectByExample(ordersExample);
                if (CollectionUtils.isEmpty(orders)) {
                    throw new BaseException("订单不存在");
                }

                Orders orders1 = orders.get(0);
                String out_trade_no = orders1.getTradeNo();

                refund(total_fee_cent, out_trade_no);

                //退款成功 更新订单状态为退款
                orders1.setStatus(-2);
                ordersMapper.updateByPrimaryKeySelective(orders1);

            }
            updateAuditDataState(infoId, raceId, 1, -1, employee.getId());

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    //修改参与者信息，修改参赛信息 修改审核以及流程信息 修改最好比赛成绩
    public void updateParticipantInfo(PaticipantDto paticipantAddDto, HttpServletRequest request) {
        try {

            //更新参与者信息
            ParticipantInfoBase participantInfoBase = new ParticipantInfoBase();
            Assembler.assemble(paticipantAddDto, participantInfoBase);
            Integer infoId = paticipantAddDto.getInfoId();
            participantInfoBase.setId(infoId);
            participantInfoBaseMapper.updateByPrimaryKeySelective(participantInfoBase);

            //更新参赛信息
            ParticipantRace participantRace = new ParticipantRace();
            Assembler.assemble(paticipantAddDto, participantRace);
            Integer raceId = paticipantAddDto.getRaceId();
            participantRace.setId(raceId);
            //支付完成，信息不合格，被驳回重填 状态更为待审核
            participantRace.setStatus(1);
            participantRaceMapper.updateByPrimaryKeySelective(participantRace);

            //修改最好比赛成绩信息，先删除原来的信息，然后在创建新的
            ParticipantInfoBaseBestScore participantInfoBaseBestScore = new ParticipantInfoBaseBestScore();
            Assembler.assemble(paticipantAddDto, participantInfoBaseBestScore);

            ParticipantInfoBaseBestScoreExample participantInfoBaseBestScoreExample = new ParticipantInfoBaseBestScoreExample();
            participantInfoBaseBestScoreExample.createCriteria().andPibIdEqualTo(participantInfoBase.getId());
            participantInfoBaseBestScoreMapper.deleteByExample(participantInfoBaseBestScoreExample);

            participantInfoBaseBestScore.setPibId(participantInfoBase.getId());
            participantInfoBaseBestScoreMapper.insertSelective(participantInfoBaseBestScore);
            //更新当前信息审核状态，由审核驳回状态改为待审核状态

            updateAuditDataState(infoId, raceId, -1, 1, 1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    //通过，等待比赛
    public void pass(Integer pibId, Integer raceId, HttpServletRequest request) {
        try {

            ParticipantRace race = participantRaceMapper.selectByPrimaryKey(raceId);
            if (!race.getStatus().equals(1)) {
                throw new BaseException("该状态下不符合报名审核通过的条件");
            }

            ParticipantRace participantRace = new ParticipantRace();
            participantRace.setId(raceId);

            // 支付成功后，信息不合格，驳回重填，状态为 -1报名驳回状态 ，
            participantRace.setStatus(2);
            participantRaceMapper.updateByPrimaryKeySelective(participantRace);

            // 修改审核表 该信息的当前状态为 1 待审核，
            // 新增审核流程 从 待支付0 -> 待审核1
            Integer empId = 1;
            Employees employee = (Employees) request.getSession().getAttribute("employee");
            empId = employee.getId();
            updateAuditDataState(pibId, raceId, 1, 2, empId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    public void resultPass(Integer infoId, Integer raceId, HttpServletRequest request) {
        ParticipantRace race = participantRaceMapper.selectByPrimaryKey(raceId);
        if (!race.getStatus().equals(3)) {
            throw new BaseException("该状态下不符合成绩通过的条件");
        }

        ParticipantRace participantRace = new ParticipantRace();
        participantRace.setId(raceId);

        participantRace.setStatus(4);
        participantRaceMapper.updateByPrimaryKeySelective(participantRace);

        Integer empId = 1;
        Employees employee = (Employees) request.getSession().getAttribute("employee");
        empId = employee.getId();
        updateAuditDataState(infoId, raceId, 3, 4, empId);
        Integer pibId = race.getPibId();
        ParticipantInfoBase participantInfoBase = participantInfoBaseMapper.selectByPrimaryKey(pibId);
        String name = participantInfoBase.getName();
        String mobile = participantInfoBase.getPersonalMobile();
        String sexStr = "先生";
        Integer sex = participantInfoBase.getSex();

        if (0 == sex) {
            sexStr = "女士";
        }
        name = name + sexStr;

        Map paramMap = Maps.newHashMap();
        paramMap.put("name", name);

        sendSmsService.sendSms(mobile, paramMap);
    }

    public void resultRefuse(Integer infoId, Integer raceId, HttpServletRequest request) {
        ParticipantRace race = participantRaceMapper.selectByPrimaryKey(raceId);
        if (!race.getStatus().equals(3)) {
            throw new BaseException("该状态下不符合成绩驳回的条件");
        }

        ParticipantRace participantRace = new ParticipantRace();
        participantRace.setId(raceId);

        participantRace.setStatus(-3);
        participantRaceMapper.updateByPrimaryKeySelective(participantRace);

        Integer empId = 1;
        Employees employee = (Employees) request.getSession().getAttribute("employee");
        empId = employee.getId();
        updateAuditDataState(infoId, raceId, 3, -3, empId);

    }


    //更新审核数据后续状态的接口
    private void updateAuditDataState(Integer pibId, Integer raceId, Integer lastStatus, Integer willStatus, Integer employeeId) {
        //更新审核表内容
        ParticipantInfoAuditExample participantInfoAuditExample = new ParticipantInfoAuditExample();
        participantInfoAuditExample.createCriteria()
                .andPibIdEqualTo(pibId)
                .andPrIdEqualTo(raceId);
        List<ParticipantInfoAudit> participantInfoAudits = participantInfoAuditMapper.selectByExample(participantInfoAuditExample);
        if (!CollectionUtils.isEmpty(participantInfoAudits)) {
            ParticipantInfoAudit participantInfoAudit = participantInfoAudits.get(0);
            participantInfoAudit.setStatus(willStatus);
            participantInfoAudit.setAuditTime(new Date());
            participantInfoAuditMapper.updateByPrimaryKeySelective(participantInfoAudit);
        }

        //插入审核流程表内容
        ParticipantInfoAuditProcess participantInfoAuditProcess = new ParticipantInfoAuditProcess();
        participantInfoAuditProcess.setPrId(raceId);
        //默认审核人 从 当前登陆人获取

        participantInfoAuditProcess.setOperationEmployee(employeeId);
        participantInfoAuditProcess.setOperationTime(new Date());
        //被驳回才可能修改
        participantInfoAuditProcess.setLastStatus(lastStatus);
        participantInfoAuditProcess.setCurrentStatus(willStatus);
        participantInfoAuditProcessMapper.insertSelective(participantInfoAuditProcess);

    }

    public void addParticipantPageParam(ParticipantPageParamDto participantPageParamDto) {
        try {
            Integer eventInformationId = participantPageParamDto.getEventInformationId();

            ParticipantPageParamExample participantPageParamExample = new ParticipantPageParamExample();
            participantPageParamExample.createCriteria().andEventInfomationIdEqualTo(eventInformationId);
            participantPageParamMapper.deleteByExample(participantPageParamExample);


            ParticipantPageParam participantPageParam = new ParticipantPageParam();
            participantPageParam.setEventInfomationId(eventInformationId);
            participantPageParam.setParamJson(JSON.toJSONString(participantPageParamDto.getParamJson()));
            participantPageParamMapper.insertSelective(participantPageParam);

        } catch (Exception e) {

            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }

    }

    public ParticipantPageParam getParticipantPageParamByEventId(Integer eventId) {
        try {
            ParticipantPageParamExample participantPageParamExample = new ParticipantPageParamExample();
            participantPageParamExample.createCriteria().andEventInfomationIdEqualTo(eventId);
            List<ParticipantPageParam> participantPageParams = participantPageParamMapper.selectByExample(participantPageParamExample);
            if (CollectionUtils.isEmpty(participantPageParams)) {
                throw new BaseException("该赛事未配置页面参数");
            }
            return participantPageParams.get(0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public Map<String, Object> getPage2Info(Integer raceId) {
        try {
            List<Map<String, Object>> page2Info = expandMapper.getPage2Info(raceId);
            if (CollectionUtils.isEmpty(page2Info)) {
                throw new BaseException("未找到数据");
            }
            return page2Info.get(0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public PageResult getAllParticipantDataByEventIdAndStatus(AllParticipantDataByEventIdDto allParticipantDataByEventIdDto) {
        try {
            PageResult pageResult = new PageResult();
            pageResult.setPage(allParticipantDataByEventIdDto.getPage());
            pageResult.setLimit(allParticipantDataByEventIdDto.getLimit());
            List<Map<String, Object>> allParticipantDataByEventId = expandMapper.getAllParticipantDataByEventIdAndStatus(allParticipantDataByEventIdDto);
            if (CollectionUtils.isEmpty(allParticipantDataByEventId)) {
                pageResult.setCount(0);
                pageResult.setList(Lists.newArrayList());
                return pageResult;
            }
            ParticipantRaceExample raceExample = new ParticipantRaceExample();
            ParticipantRaceExample.Criteria criteria = raceExample.createCriteria();
            criteria.andEventIdEqualTo(allParticipantDataByEventIdDto.getEventId());

            if (allParticipantDataByEventIdDto.getStatus() != null) {
                criteria.andStatusIn(allParticipantDataByEventIdDto.getStatus());
            }

            if (allParticipantDataByEventIdDto.getGroupId() != null) {
                criteria.andGroupIdEqualTo(allParticipantDataByEventIdDto.getGroupId());
            }

            if (allParticipantDataByEventIdDto.getOnlineSelect() != null) {
                criteria.andOnlineEqualTo(allParticipantDataByEventIdDto.getOnlineSelect());
            }

            int count = participantRaceMapper.countByExample(raceExample);
            pageResult.setCount(count);
            pageResult.setList(allParticipantDataByEventId);
            return pageResult;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public ParticipantRace getParticipantRaceById(Integer raceId) {
        try {
            ParticipantRace participantRace = participantRaceMapper.selectByPrimaryKey(raceId);
            if (ObjectUtil.isNullObj(participantRace)) {
                throw new BaseException("未找到数据");
            }
            return participantRace;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    public ParticipantInfoBase getParticipantInfoBaseById(Integer pibId) {

        try {
            ParticipantInfoBase participantInfoBase = participantInfoBaseMapper.selectByPrimaryKey(pibId);
            if (ObjectUtil.isNullObj(participantInfoBase)) {
                throw new BaseException("未找到数据");
            }
            return participantInfoBase;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    public EventPrice getEventPriceById(Integer priceId) {

        try {
            EventPrice eventPrice = eventPriceMapper.selectByPrimaryKey(priceId);
            if (ObjectUtil.isNullObj(eventPrice)) {
                throw new BaseException("未找到数据");
            }
            return eventPrice;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public String getParticipantCode(Integer raceId) {
        ParticipantRace pr1 = participantRaceMapper.selectByPrimaryKey(raceId);
        Integer groupId = pr1.getGroupId();
        EventGroup eventGroup = eventGroupMapper.selectByPrimaryKey(groupId);
        if (ObjectUtil.isNullObj(eventGroup)) {
            throw new BaseException("该赛事没有设置组别");
        }
        String code = eventGroup.getCode();
        Integer digits = eventGroup.getDigits();
        Integer currentMax = eventGroup.getCurrentMax();
        Integer begin = eventGroup.getBegin();
        Integer end = eventGroup.getEnd();

        Integer digTen = Double.valueOf(Math.pow(10.0, digits)).intValue();
        System.out.println(digTen);
        if (digits == 1) {
            digTen = 0;
        }

        Integer i = digTen + currentMax + 1;
        String substring = ObjectUtil.toString(i);

        if (digits >= 2) {
            substring = substring.substring(1, substring.length());
        }
        eventGroup.setCurrentMax(currentMax + 1);
        eventGroupMapper.updateByPrimaryKey(eventGroup);

        return code + substring;

    }

    private Map undefined(String openId, Integer total_fee_cent, String out_trade_no) {
        String openid = openId;
        MyWxPayConfig config = null;
        WXPay wxpay = null;
        try {
            config = new MyWxPayConfig();
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成的随机字符串
        String nonce_str = WXPayUtil.generateNonceStr();
        //获取客户端的ip地址
        //获取本机的ip地址
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String spbill_create_ip = addr.getHostAddress();
        //支付金额，需要转成字符串类型，否则后面的签名会失败
        //商品描述
        String body = "戈越无疆微信支付";
        //商户订单号

        //统一下单接口参数
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", body);
        data.put("out_trade_no", out_trade_no);
        data.put("total_fee", String.valueOf(total_fee_cent));
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("notify_url", config.getNotifyUrl());
        data.put("trade_type", MyWxPayConfig.TRADETYPE);
        data.put("openid", openid);
        data.put("mch_id", config.getMchID());
        data.put("appid", config.getAppID());
        data.put("nonce_str", nonce_str);
        data.put("sign_type", "MD5");
        logger.info(ObjectUtil.toString(data));
        try {
            //获取带有 sign 的 XML 格式字符串
            String xmlParam = WXPayUtil.generateSignedXml(data, config.getKey(), WXPayConstants.SignType.MD5);
            Map<String, String> mapResult = doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlParam);
            logger.info(ObjectUtil.toString(mapResult));
            //判断返回状态码return_code
            if (WXPayConstants.WX_RETURN_CODE_FAIL.equals(mapResult.get(WXPayConstants.FIELD_RETURN_CODE))) {
                throw new BaseException(mapResult.get("return_msg"));
            }

            //判断业务结果result_code
            if (WXPayConstants.WX_RESULT_CODE_FAIL.equals(mapResult.get(WXPayConstants.FIELD_RESULT_CODE))) {
                throw new BaseException(mapResult.get("err_code_des"));
            }
            //返回的map
            Map<String, String> resultMap = new HashMap<String, String>(7);
            resultMap.put("appId", config.getAppID());
            resultMap.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));
            resultMap.put("nonceStr", nonce_str);
            resultMap.put("package", "prepay_id=" + mapResult.get("prepay_id"));
            resultMap.put("signType", "MD5");
            resultMap.put("paySign", WXPayUtil.generateSignature(resultMap, config.getKey(), WXPayConstants.SignType.MD5));
            resultMap.put("outTradeNo", out_trade_no);
            return resultMap;

        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * POST请求
     *
     * @param url      请求的URL地址
     * @param xmlParam xml字符串
     * @return
     * @throws Exception
     */
    private Map<String, String> doPost(String url, String xmlParam) throws Exception {
        HttpClient httpClient = new HttpClient(url);
        httpClient.setHttps(true);
        httpClient.setXmlParam(xmlParam);
        httpClient.post();
        String xmlResult = httpClient.getContent();

        //把获取xml数据转成map
        return WXPayUtil.xmlToMap(xmlResult);
    }

    /**
     * 微信支付完成后 通知 成功后
     *
     * @param request
     * @return
     */
    public String notice(HttpServletRequest request) {
        logger.info("=========begin======wx======pay=====notice");
        Map<String, String> resultMap = WXPayUtil.notify(request);
        logger.info("=========resultMap=======" + ObjectUtil.toString(resultMap));
        if ("SUCCESS".equals(resultMap.get("return_code"))) {
            logger.info("=========into=====paySuccess==");
            String s = resultMap.get("out_trade_no");
            OrdersExample ordersExample = new OrdersExample();
            ordersExample.createCriteria().andTradeNoEqualTo(s);
            List<Orders> orders = ordersMapper.selectByExample(ordersExample);
            if (CollectionUtils.isEmpty(orders)) {
                return WXPayUtil.returnXML("FAILED", "failed");
            }
            Integer pibId = orders.get(0).getPibId();
            Integer eventPriceId = orders.get(0).getEventPriceId();
            ParticipantRaceExample participantRaceExample = new ParticipantRaceExample();
            participantRaceExample.createCriteria().andEventPriceIdEqualTo(eventPriceId).andPibIdEqualTo(pibId);
            List<ParticipantRace> participantRaces = participantRaceMapper.selectByExample(participantRaceExample);
            if (CollectionUtils.isEmpty(participantRaces)) {
                return WXPayUtil.returnXML("FAILED", "failed");
            }
            Integer raceId = participantRaces.get(0).getId();

            String tradeNo = orders.get(0).getTradeNo();
            paySuccess(pibId, raceId, tradeNo, request);
        }
        return WXPayUtil.returnXML(resultMap.get("return_code"), resultMap.get("return_msg"));
    }

    public void updateRacePartCode(Integer raceId, String code) {
        try {
            ParticipantRace participantRace1 = participantRaceMapper.selectByPrimaryKey(raceId);
            if (1 != participantRace1.getStatus()) {
                throw new BaseException("该状态下不可修改参赛码！");
            }
            ParticipantRaceExample participantRaceExample = new ParticipantRaceExample();
            participantRaceExample.createCriteria().andParticipantCodeEqualTo(code);
            List<ParticipantRace> participantRaces = participantRaceMapper.selectByExample(participantRaceExample);
            if (!CollectionUtils.isEmpty(participantRaces)) {
                throw new BaseException("该参赛码已经被分配，请分配其他号码！");
            }
            ParticipantRace participantRace = new ParticipantRace();
            participantRace.setId(raceId);
            participantRace.setParticipantCode(code);
            participantRaceMapper.updateByPrimaryKeySelective(participantRace);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 支付选择奖品金额为0的 支付方式
     *
     * @param pibId
     * @param eventPriceId
     * @param tradeType
     */
    public void payZero(Integer pibId, Integer eventPriceId, Integer tradeType) {
        String tradeNo = String.valueOf(idWorker.nextId());
        Orders order = new Orders();
        order.setTradeNo(tradeNo);
        order.setPibId(pibId);
        order.setEventPriceId(eventPriceId);
        order.setStatus(0);
        EventPrice eventPrice = eventPriceMapper.selectByPrimaryKey(eventPriceId);
        if (ObjectUtil.isNullObj(eventPrice)) {
            throw new BaseException("套餐信息不存在");
        }
        order.setAmont(eventPrice.getPrice());
        order.setTradeType(tradeType);
        order.setTradeTime(new Date());
        //插入订单表
        ordersMapper.insertSelective(order);
        ParticipantRaceExample participantRaceExample = new ParticipantRaceExample();
        participantRaceExample.createCriteria().andEventPriceIdEqualTo(eventPriceId).andPibIdEqualTo(pibId);
        List<ParticipantRace> participantRaces = participantRaceMapper.selectByExample(participantRaceExample);
        if (CollectionUtils.isEmpty(participantRaces)) {
            throw new BaseException("失败,参赛信息为空");
        }
        Integer raceId = participantRaces.get(0).getId();

        ParticipantRace participantRace = new ParticipantRace();
        participantRace.setId(raceId);
        // 修改比赛信息状态为 1 待审核，
        participantRace.setStatus(1);

        // 安排编号
        String participantCode = getParticipantCode(raceId);
        participantRace.setParticipantCode(participantCode);

        participantRaceMapper.updateByPrimaryKeySelective(participantRace);

        // 修改审核表 该信息的当前状态为 1 待审核，
        // 新增审核流程 待审核1
        updateAuditDataState(pibId, raceId, 0, 1, 1);
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andTradeNoEqualTo(tradeNo);
        List<Orders> orders = ordersMapper.selectByExample(ordersExample);
        if (CollectionUtils.isEmpty(orders)) {
            throw new BaseException("订单号不存在");
        }
        Orders order1 = orders.get(0);
        order1.setStatus(1);
        //更新订单状态
        ordersMapper.updateByPrimaryKey(order1);

        //插入账单表
        BillDetail billDetail = new BillDetail();
        billDetail.setPibId(pibId);
        billDetail.setOrderId(order.getId());
        billDetail.setBeforeMoney(BigDecimal.ZERO);
        billDetail.setMoney(order.getAmont());
        billDetail.setAfterMoney(order.getAmont());
        billDetail.setOrderType(1);
        billDetail.setOperateTime(new Date());
        billDetail.setOrderStatus(1);

        billDetailMapper.insertSelective(billDetail);

        Map<String, Object> page2Info = getPage2Info(raceId);
        Map<String, Object> paramMap = Maps.newHashMap();
        String mobile = (String) page2Info.get("personal_mobile");
        paramMap.put("name", page2Info.get("name"));
        paramMap.put("event_info_name", page2Info.get("event_info_name"));
        paramMap.put("participant_code", page2Info.get("participant_code"));
        paramMap.put("event_info_begin_time", page2Info.get("event_info_begin_time"));
        paramMap.put("event_info_place", page2Info.get("event_info_place"));
        //todo 暂时取消发送短信 改手动
//        sendSmsService.sendSms(mobile, paramMap);


    }


    public Map getAllInfoByOpenIdAndEventId(AllParticipantDataDto allParticipantDataDto) {
        try {
            logger.info("=========allParticipantDataDto==========" + ObjectUtil.toString(allParticipantDataDto));
            Map<String, Object> allInfoByOpenIdAndEventId = expandMapper.getAllInfoByOpenIdAndEventId(allParticipantDataDto);
            if (ObjectUtil.isNullObj(allInfoByOpenIdAndEventId)) {
                throw new BaseException("暂无数据");
            }
            return allInfoByOpenIdAndEventId;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public void updateBestScorePic(UpdateBestScorePicDto updateBestScorePicDto, HttpServletResponse response) {
        try {
            ParticipantRaceExample participantRaceExample = new ParticipantRaceExample();
            participantRaceExample.createCriteria()
                    .andEventIdEqualTo(updateBestScorePicDto.getEventId())
                    .andParticipantCodeEqualTo(updateBestScorePicDto.getCode());
            List<ParticipantRace> participantRaces = participantRaceMapper.selectByExample(participantRaceExample);
            if (CollectionUtils.isEmpty(participantRaces)) {
                throw new BaseException("此赛事该号码不存在, 请重新核对后提交");
            }

            ParticipantRace participantRace = participantRaces.get(0);
            if (participantRace.getStatus() != 2) {
                throw new BaseException("该状态下不允许上传成绩");
            }
            String pic = updateBestScorePicDto.getPic();
            //去掉结尾的 "，"
            pic = pic.substring(0, pic.length() - 1);
            participantRace.setFinalPic(pic);
            participantRace.setFinalDistance(updateBestScorePicDto.getFinalDistance());
            participantRace.setFinalResult(updateBestScorePicDto.getFinalResult());
            participantRace.setStatus(3);

            participantRaceMapper.updateByPrimaryKeySelective(participantRace);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    public String getRaceCertificate(Integer eventId, String code, HttpServletResponse response) {
        try {
            ParticipantRaceExample participantRaceExample = new ParticipantRaceExample();
            participantRaceExample.createCriteria()
                    .andEventIdEqualTo(eventId)
                    .andParticipantCodeEqualTo(code);
            List<ParticipantRace> participantRaces = participantRaceMapper.selectByExample(participantRaceExample);
            if (CollectionUtils.isEmpty(participantRaces)) {
                throw new BaseException("此赛事该号码不存在, 请重新核对后提交");
            }
            ParticipantRace participantRace = participantRaces.get(0);
            if (Integer.valueOf(String.valueOf(participantRace.getStatus())) < 4) {
                throw new BaseException("请先上传完赛成绩，等待审核通过后，进行证书下载");
            }
            String grade = participantRace.getFinalResult();
            Integer pibId = participantRace.getPibId();
            Integer groupId = participantRace.getGroupId();
            EventGroup eventGroup = eventGroupMapper.selectByPrimaryKey(groupId);
            String eventGroupName = eventGroup.getName();
            ParticipantInfoBase participantInfoBase = participantInfoBaseMapper.selectByPrimaryKey(pibId);
            String name = participantInfoBase.getName();
            Integer sex = participantInfoBase.getSex();
            String genderStr = "男";
            if (0 == sex) {
                genderStr = "女";
            }
            EventInformation eventInformation = eventInformationMapper.selectByPrimaryKey(eventId);
            String certificate = eventInformation.getCertificate();
            URL url = new URL(certificate);
            ImageIcon bufImg = new ImageIcon(url);
            BufferedImage img = new BufferedImage(1217, 856, BufferedImage.TYPE_INT_RGB);
            Graphics2D g0 = (Graphics2D) img.getGraphics();
            g0.drawImage(bufImg.getImage(), 0, 0, 1217, 856, null);
            g0.dispose();
            Graphics2D g = img.createGraphics();
            Font font = new Font("微软雅黑", Font.PLAIN, 27);
            g.setFont(font);
            g.setColor(Color.BLACK);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g.drawString(name, 620 * 3 / 2, 265);
            g.drawString(genderStr, 635 * 3 / 2, 325);
            g.drawString(participantRace.getParticipantCode(), 620 * 3 / 2, 385);
            g.drawString(eventGroupName, 555 * 3 / 2, 445);
            g.drawString(grade, 615 * 3 / 2, 505);
            g.dispose();
            // 输出新图片到 ServletOutputStream
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            response.setContentType("image/jpeg");
            ImageIO.write(img, "jpg", os);
            return ossUtil.putDataByByte(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public String getNumberBookByPersonMobileAndEventId(GetParticipantDataByPersonalMobileAndEventIdDto getParticipantDataByDocumentNumAndEventIdDto, HttpServletResponse response) {
        try {
            Map allInfoByOpenIdAndEventId = getNumberBookByPersonMobileAndEventId(getParticipantDataByDocumentNumAndEventIdDto);
            //报名审核通过后才显示
            if (Integer.valueOf(String.valueOf(allInfoByOpenIdAndEventId.get("status"))) < 2) {
                throw new BaseException("该状态下信息暂不支持生成号码布");
            }
            String participantCode = String.valueOf(allInfoByOpenIdAndEventId.get("participantCode"));
            String name = String.valueOf(allInfoByOpenIdAndEventId.get("name"));
            String group_name = String.valueOf(allInfoByOpenIdAndEventId.get("group_name"));
            Color color = new Color(255, 80, 84);
            if (group_name.equals("半程马拉松(21.0975KM)")) {
                color = new Color(110, 187, 235);
            }
            if (group_name.equals("全程马拉松(42.195KM)")) {
                color = new Color(206, 54, 209);
            }

            String numberbook = (String) allInfoByOpenIdAndEventId.get("numberbook");
            BufferedImage imageLocal = null;

            try {
                imageLocal = ImageIO.read(new URL(numberbook));
            } catch (IOException e) {
                e.printStackTrace();
                throw new BaseException(e.getMessage());
            }
            Graphics2D g = imageLocal.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Font font = new Font("造字工房力黑体", Font.PLAIN, 190 * 6);
            g.setFont(font);
            g.setColor(color);
            g.drawString(participantCode, 380 * 6, 400 * 6);

            Graphics2D g1 = imageLocal.createGraphics();
            g1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g1.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
            g1.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Font font1 = new Font("造字工房力黑体", Font.PLAIN, 80 * 6);
            g1.setFont(font1);
            g1.setColor(color);
            if (name.length() > 3) {
                g1.drawString(name, 50 * 6, 385 * 6);
            } else if (name.length() == 3) {
                g1.drawString(name, 75 * 6, 385 * 6);
            } else {
                g1.drawString(name, 100 * 6, 385 * 6);
            }

            g.dispose();
            g1.dispose();
            // 输出新图片到 ServletOutputStream
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            response.setContentType("image/jpeg");
            ImageIO.write(imageLocal, "jpg", os);
            return ossUtil.putDataByByte(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    private Map getNumberBookByPersonMobileAndEventId(GetParticipantDataByPersonalMobileAndEventIdDto getParticipantDataByPersonalMobileAndEventIdDto) {
        try {
            logger.info("=========getParticipantDataByPersonalMobileAndEventIdDto==========" + ObjectUtil.toString(getParticipantDataByPersonalMobileAndEventIdDto));
            Map<String, Object> allInfoByOpenIdAndEventId = expandMapper.getAllInfoByByPersonalMobileAndEventId(getParticipantDataByPersonalMobileAndEventIdDto);
            if (ObjectUtil.isNullObj(allInfoByOpenIdAndEventId)) {
                throw new BaseException("暂无数据");
            }
            return allInfoByOpenIdAndEventId;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    /**
     * 申请退款
     *
     * @return
     */
    public String refund(Integer total_fee_cent, String out_trade_no) throws Exception {
        MyWxPayConfig config = new MyWxPayConfig();
        WXPay wxpay = new WXPay(config);
        //统一下单接口参数
        try {
            config = new MyWxPayConfig();
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成的随机字符串
        String nonce_str = WXPayUtil.generateNonceStr();

        HashMap<String, String> data = new HashMap<String, String>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", nonce_str);
        data.put("out_refund_no", out_trade_no);
        data.put("out_trade_no", out_trade_no);
        data.put("refund_fee", String.valueOf(total_fee_cent));
        data.put("total_fee", String.valueOf(total_fee_cent));

        Map<String, String> resp = null;
        try {
            resp = wxpay.refund(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println(resp);
        //返回状态码
        String return_code = resp.get("return_code");
        //返回信息
        String return_msg = resp.get("return_msg");

        String resultReturn = null;
        if ("SUCCESS".equals(return_code)) {
            //业务结果
            String result_code = resp.get("result_code");
            //错误代码描述
            String err_code_des = resp.get("err_code_des");
            if ("SUCCESS".equals(result_code)) {
                //表示退款申请接受成功，结果通过退款查询接口查询
                //修改用户订单状态为退款申请中（暂时未写）
                resultReturn = "退款申请成功";
            } else {
                logger.info("订单号:{}错误信息:{}", err_code_des);
                throw new BaseException(err_code_des);
            }
        } else {
            logger.info("订单号:{}错误信息:{}", return_msg);
            throw new BaseException(return_msg);
        }
        return JSON.toJSONString(resultReturn);
    }


    public String getRaceGroupByPartCode(Integer eventId, String code) {

        EventGroupExample eventGroupExample = new EventGroupExample();
        eventGroupExample.createCriteria().andBelongEventIdEqualTo(eventId);
        List<EventGroup> eventGroups = eventGroupMapper.selectByExample(eventGroupExample);
        if (CollectionUtils.isEmpty(eventGroups)) {
            throw new BaseException("赛事信息不存在");
        }
        String raceGroup = "";
        for (int i = 0; i < eventGroups.size(); i++) {
            String begin = code.substring(0, 1);
            String codeBegin = eventGroups.get(i).getCode();
            if (StringUtils.startsWithIgnoreCase(begin, codeBegin)) {
                raceGroup = eventGroups.get(i).getName();
            }
        }

        ArrayList<Object> execList = Lists.newArrayList();
        Collections.addAll(execList, raceGroup.split("\\("));
        if (CollectionUtils.isEmpty(execList)) {
            throw new BaseException("项目不存在");
        }
        String a = String.valueOf(execList.get(1));
        return a.substring(0, a.length() - 1);
    }
}
